#include "mainwindow.h"
#include "ui_mainwindow.h"

char buffer[512];

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serialPort=new QSerialPort(this);
    QStringList portNames;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        portNames<<info.portName();
    }
    ui->combo_com->addItems(portNames);
    ui->lcdNumber_staus->setMode(QLCDNumber::Hex);
    ui->lcdNumber_staus->display("OFF");
    connected=false;
    //设置接收数据间隔
    receiveInterval=1;
    //init timer
    timer = new QTimer(this);
    connect(serialPort, &QSerialPort::readyRead, this, &MainWindow::readSerialData);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_connect_clicked()
{
    //连接按钮点击
    qDebug("btn connect clicked.");
    serialPort->setPortName(ui->combo_com->currentText());
    serialPort->setBaudRate(ui->combo_baud->currentText().toInt());
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setParity(QSerialPort::NoParity);
    if (true == serialPort->open(QIODevice::ReadWrite))
    {
        connected=true;
        ui->lcdNumber_staus->display("0P");
        //[receiveInterval]ms读一次
        timer->start(receiveInterval);
        QMessageBox::information(this, "提示", "串口打开成功");
    }
    else
    {
        QMessageBox::critical(this, "啊偶", "串口打开失败");
    }
}


void MainWindow::on_pushButton_disconnect_clicked()
{
    //断开按钮点击
    qDebug("btn disconnect clicked.");
    connected=false;
    ui->lcdNumber_staus->display("0FF");
    timer->stop();
    serialPort->close();
    QMessageBox::information(this, "提示","串口已关闭");
}


void MainWindow::on_pushButton_refresh_clicked()
{
    qDebug("btn refresh clicked.");
    //刷新可用的串口
    QString oldChoice=ui->combo_com->currentText();
    bool oldStillThere=false;
    ui->combo_com->clear();
    QStringList portNames;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        qDebug() << "Name: " << info.portName();
        qDebug() << "Description: " << info.description();
        qDebug() << "Manufacturer: " << info.manufacturer();
        qDebug() << "Serial Number: " << info.serialNumber();
        qDebug() << "System Location: " << info.systemLocation();
        portNames<<info.portName();
        if(info.portName()==oldChoice)
            oldStillThere=true;
    }
    ui->combo_com->addItems(portNames);
    if(oldStillThere)
        ui->combo_com->setCurrentText(oldChoice);
}

void MainWindow::readSerialData(){
    //读取串口数据
    QByteArray readComData = serialPort->readAll();

    //将读到的数据显示到数据接收区的text中
    if(readComData != nullptr)
    {
        ui->textBrowser_receive->append(readComData);
    }
    QString str=ui->textBrowser_receive->toPlainText();
    if(str.count()>200000){
        //timer->stop();
        str = str.mid(str.count()-10000);
        ui->textBrowser_receive->clear();
        ui->textBrowser_receive->setText(str);
        ui->textBrowser_receive->verticalScrollBar()
                ->setValue(ui->textBrowser_receive->verticalScrollBar()->maximum());
        //timer->start(receiveInterval);
    }
    //清除缓冲区
    readComData.clear();
}

void MainWindow::readSerialByte(){
    //使用字符数组作缓冲，读取数据。

}

void MainWindow::on_pushButton_send_clicked()
{
    //发送按钮点击
    qDebug("btn send clicked.");
    if(!connected){
        QMessageBox::critical(this, "糟糕", "串口还未打开！");
        return;
    }
    QString str=ui->lineEdit_send->text();
    QByteArray str_byte=str.toUtf8();
    serialPort->write(str_byte);
}


void MainWindow::on_pushButton_gen_clicked()
{
    //生成数据按钮点击
    qDebug("btn generate clicked.");
    //data length (Byte)
    int dataLen=ui->lineEdit_len->text().toInt();
    //clear old data
    testData="";
    char tmp;
    for(int i=0; i<dataLen; ++i){
        //generate a random byte
        tmp=QRandomGenerator::global()->bounded(65535);
        testData.append(tmp);
    }
    qDebug()<<"data length(B): "<<testData.length();
    //calc hashcode
    hashcode = QCryptographicHash::hash(testData, QCryptographicHash::Md5);
    ui->textBrowser_sum->setText("MD5:");
    ui->textBrowser_sum->append(hashcode.toHex());
    ui->textBrowser_sum->append("\ndata:");
    ui->textBrowser_sum->append(testData.toHex(':'));
}


void MainWindow::on_pushButton_start_clicked()
{
    qDebug("btn start clicked.");
    if(!connected){
        QMessageBox::critical(this, "糟糕", "串口还未打开！");
        return;
    }
    int datalen=testData.length();
    int sendnum=ui->lineEdit_num->text().toInt();
    serialPort->write((char*)&datalen, 4);
    serialPort->write((char*)&sendnum, 4);
}

